package com.qf.common.core.interceptor;

import com.qf.common.core.annotation.NoLoginCheck;
import com.qf.common.core.utils.JwtUtils;
import com.qf.common.core.utils.UserUtils;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.lang.reflect.Method;
import java.util.Map;

/**
 * Author hehecheng
 * Date 2024/10/28
 * 祝我们都能遇见真诚的人
 * 见字如面
 */
public class LoginInterceptor implements HandlerInterceptor {

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        System.out.println("请求路径"+request.getRequestURL());
        if (handler instanceof HandlerMethod) {
            // spring中，将控制层的方法封装为HandlerMethod
            HandlerMethod handlerMethod = (HandlerMethod) handler;
            Method method = handlerMethod.getMethod();
            //判断方法上是否存在指定的注解
            boolean annotationPresent = method.isAnnotationPresent(NoLoginCheck.class);
            if (annotationPresent) {
                //如果使用了@NoLoginCheck 注解，直接放行
                return true;
            }

            String token = request.getHeader("Token");

            if (token == null || token.isEmpty()) {
                throw new RuntimeException("请登录");
            }

            try {
                Map<String, Object> claims = JwtUtils.parseJWT(token);
                Integer uid = (Integer) claims.get("uid");
                // 将uid存入到ThreadLocal中
                UserUtils.setUid(uid);

            } catch (Exception e) {
                throw new RuntimeException("请重新登录");
            }
        }

        return true;
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        // 删除数据，防止内存泄漏
        UserUtils.removeUid();
    }
}
